package com.zhengyisky.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.zhengyisky.entity.LifeCallbackParam;
import com.zhengyisky.utils.HttpUtils;
import com.zhengyisky.utils.MD5Utils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.ExecutorService;

@Controller

public class ResultController {

    @Value("${tianyan.appid}")
    private String appid;

    @Value("${tianyan.secret}")
    private String secret;


    //使用oss的一个域名
    @Value("${alibaba.oss.endpoint}")
    private String endpoint;
    //使用oss的一个key
    @Value("${alibaba.oss.access_key}")
    private String accessKeyId;
    //使用oss的一个密钥
    @Value("${alibaba.oss.access_secret}")
    private String accessKeySecret;

    @Autowired
    private ExecutorService threadPool;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/upload")
    @ResponseBody
    public Map upload(MultipartFile file) throws IOException {
        //时间戳
        String timestamp = System.currentTimeMillis() + "";
        //调用168行方法，传入时间戳，符合接口需要的数据
        String sign = this.tianyanSign(timestamp);
        InputStream inputStream = file.getInputStream();

        //为了优化用户等待时间，开启线程单独上传
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("OSS上传开始");
                //将文件上传到OSS
                String filename = file.getOriginalFilename();
                String picName = UUID.randomUUID().toString() + filename.substring(filename.lastIndexOf("."));
                // 创建OSSClient实例。
                OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
                ossClient.putObject("bwd2021", "idcard/" + picName, inputStream);
                // 关闭OSSClient。
                ossClient.shutdown();
                System.out.println("OSS上传完毕");
            }
        };
        threadPool.submit(runnable);

        //得到base64图片
        byte[] data = new byte[inputStream.available()];
        inputStream.read(data);
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Str = encoder.encode(data);

        //使用URL进行OCR识别（域名是数脉数据）
        String ocrUrl = "https://api.shumaidata.com/v2/idcard/ocr";
        //httpClient   restTemplate
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(ocrUrl);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("appid",appid));
        list.add(new BasicNameValuePair("timestamp",timestamp));
        list.add(new BasicNameValuePair("sign",sign));
        list.add(new BasicNameValuePair("image",base64Str));


        Map info = null;
        HttpEntity entity = new UrlEncodedFormEntity(list);
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);
        String json = EntityUtils.toString(response.getEntity(), "UTF-8");
        //把json对象转换成map集合
        Map map = JSONObject.parseObject(json, Map.class);
        if((Boolean) map.get("success")==true && (Integer)map.get("code")==200){
            Map res = (Map)map.get("data");
            info = (Map)res.get("info");
        }

        return info;
    }

    @RequestMapping("/mobileCheck")
    @ResponseBody
    public Boolean mobileCheck(String mobile,@RequestBody Map map){
        String timestamp = System.currentTimeMillis() + "";
        //参数
        String name = (String) map.get("name");
        String idcard = (String) map.get("number");
        //接口地址
        String url = "https://api.shumaidata.com/v4/mobile_three/transfer";
        String sign = MD5Utils.encrypt(appid+"&"+timestamp+"&"+secret);
        System.out.println("sign: "+sign);

        Map<String,Object> params = new HashMap<String,Object>();
        params.put("appid",appid);
        params.put("timestamp",timestamp);
        params.put("sign",sign);
        params.put("name", name);
        params.put("mobile", mobile);
        params.put("idcard", idcard );

        //请下载 HttpUtils文件，地址为 https://file.tianyandata.cn/demo/utils/HttpUtils.java
        String result = HttpUtils.get(url,null,params);
        Map resultMap = JSONObject.parseObject(result, Map.class);
        Map data = (Map) resultMap.get("data");
        if(data.get("result").equals("0")){
            //将手机号和身份信息存储起来
            redisTemplate.opsForHash().putAll(mobile,map);
            return true;
        }else{
            return false;
        }
    }

    @RequestMapping("/face")
    public String toPage(HttpServletRequest request, String mobile){
        //进行客户端校验，判断是否来源于PC，来源于PC拒绝
        String user_agent = request.getHeader("User-Agent");
        //移动端操作系统：iPhone Android （黑莓 鸿蒙 windowsPphone 塞班）
        if(user_agent.indexOf("Android")<0 && user_agent.indexOf("iPhone")<0){
            return "redirect:/faceError.html";
        }
        String callbackUrl = "http://bwd.5gzvip.idcfengye.com/result";
        String returnUrl = "http://bwd.5gzvip.idcfengye.com/wait.html";
        String timestamp = System.currentTimeMillis() + "";
        String sign = this.tianyanSign(timestamp);
        String url = "https://lifeh5.shumaidata.com/index.html#/?appid="+appid+"&callbackUrl="+callbackUrl+"&returnUrl="+returnUrl+"&complexity=2&timestamp="+timestamp+"&sign="+sign+"&uid="+mobile+"&title=八维贷";
        return "redirect:"+url;
    }

    private String tianyanSign(String time){
         return DigestUtils.md5Hex(appid+"&"+time+"&"+secret);
    }


    @RequestMapping("/result")
    @ResponseBody
    public void result(@RequestBody LifeCallbackParam param) throws IOException {
        Map resultInfo = param.getInfo();
        Integer code = (Integer) resultInfo.get("code");
        if(code!=200){
            return;
        }


        // 根据uid（手机号）查询Redis 获取身份证号和姓名
        String mobile = param.getUid();
        Map info = redisTemplate.opsForHash().entries(mobile);
        // 根据图片ID拿到图片流,is->base64
        Map data = (Map) resultInfo.get("data");
        String imageId = (String) data.get("feature_image_id");
        String picUrl = "https://api.shumaidata.com/v2/life/check/image?imageId="+imageId;
        System.out.println(picUrl);
        //如果结果是成功，则需要判断是否认证合一
        //从活体检测的结果中，取出活体检测时候的照片


        String name = (String) info.get("name");
        System.out.println(name);
        String idcard = (String) info.get("number");
        System.out.println(idcard);
        //接口地址
        String url = "https://api.shumaidata.com/v4/face_id_card/compare";

        String timestamp = System.currentTimeMillis() + "";
        String sign = this.tianyanSign(timestamp);

        Map<String,String> headers = new HashMap<String,String>();
        headers.put("Content-Type","application/x-www-form-urlencoded");

        Map<String,Object> params = new HashMap<String,Object>();
        params.put("appid",appid);
        params.put("timestamp",timestamp);
        params.put("sign",sign);
        params.put("name", name);
        params.put("idcard", idcard);
        params.put("url", picUrl);


        String result = HttpUtils.postForm(url,headers,params);
        Map map = JSONObject.parseObject(result, Map.class);
        Map resultData = (Map) map.get("data");
        //0.45分以上为同一人
        if(resultData.get("msg").equals("系统判断为同一人")){
            redisTemplate.opsForValue().set("res"+mobile,"true");
        }else{
            redisTemplate.opsForValue().set("res"+mobile,"false");
        }

    }

    @RequestMapping("getFinalResult")
    @ResponseBody
    public Boolean getFinalResult(String mobile){
        String result = redisTemplate.opsForValue().get("res" + mobile);
        return result.equals("true");
    }

}
